package com.lottemall.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lottemall.common.enums.ExceptionEnume;
import com.lottemall.common.exception.LtException;
import com.lottemall.common.vo.PageResult;
import com.lottemall.item.mapper.BrandMapper;
import com.lottemall.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 品牌业务
 */
@Service
public class BrandService {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private BrandMapper brandMapper;

    /**
     * 查询分页品牌信息
     *
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param key
     * @return
     */
    public PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        //使用分页助手，这里开启，直接将接下来的sql进行拦截自动拼上条件:这个十分的智能 (当前页，每页显示)
        PageHelper.startPage(page, rows);

        /**
         * where 'name' like '%x%' or letter = 'x'
         * order by id desc
         */
        //过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNotBlank(key)) { //如果类目名字不为空
            //过滤条件(模糊和首字母，这里转换成大写，因为数据库中统一的是大写)
            example.createCriteria().orLike("name", "%" + key + "%")
                    .orEqualTo("letter", key.toUpperCase());
        }

        //排序
        if (StringUtils.isNotBlank(sortBy)) {
            //首先定义排序语句(属性字段加是如何排序判断   :降序、升序)
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }
        //查询
        List<Brand> brands = brandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(brands)) {
            //抛出异常，进行统一返回给前端
            throw new LtException(ExceptionEnume.BRAND_NOT_FOUND);
        }
        //解析分页结果(里面有分页的详细信息)
        PageInfo<Brand> info = new PageInfo<>(brands);
        return new PageResult<>(info.getTotal(), brands);
    }

    /**
     * 新增品牌
     *
     * @param brand
     * @param cids
     */
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        brand.setId(null);
        int count = brandMapper.insert(brand);
        if (count != 1) {
            throw new LtException(ExceptionEnume.BRAND_SAVE_ERROR);
        }
        //新增中间表（tb_category_brand）
        for (Long cid : cids) {
            //这里的商品分类id不用担心没有，因为上面添加成功了，mybatis已经自动帮我们回显了（类似hibernate中的那个几个状态）
            count = brandMapper.insertCategoryBrand(cid, brand.getId());
            if (count != 1) {
                throw new LtException(ExceptionEnume.BRAND_SAVE_ERROR);
            }
        }
    }

    /**
     * 根据品牌id查询品牌实体
     *
     * @param id
     * @return
     */
    public Brand queryById(Long id) {
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null) {
            throw new LtException(ExceptionEnume.BRAND_NOT_FOUND);
        }
        return brand;
    }

    /**
     * 根据商品类型cid查询品牌
     * @param cid
     * @return
     */
    public List<Brand> queryBrandByCid(Long cid) {
        List<Brand> brandList = brandMapper.queryByCategoryId(cid);
        if (CollectionUtils.isEmpty(brandList)){
            throw new LtException(ExceptionEnume.BRAND_NOT_FOUND);
        }
        return brandList;
    }

    /**
     * 根据品牌ids,查询出品牌集合
     * @param ids
     * @return
     */
    public List<Brand> queryBrandByIds(List<Long> ids) {
        List<Brand> brandList = brandMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(brandList)){
            throw new LtException(ExceptionEnume.BRAND_NOT_FOUND);
        }
        return brandList;
    }
}
